package com.cssl.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.cssl.utils.CommonUtils;
import org.apache.flink.api.common.functions.RichFilterFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.text.SimpleDateFormat;
import java.util.Properties;

/**
 * @Author: chen
 * @Date: 2021/11/14 16:52
 * @Desc: 读取 dwd_page_log 主题数据 , 过滤 uv 数据发送到 dwm_unique_visit 主题
 */
public class UniqueVisitApp {
    public static void main(String[] args) throws Exception {
        //1. 获取执行环境
        Properties properties = CommonUtils.getProperties();
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2. 读取 kafka dwd_page_log 主题的数据
        String dwdPageTopic = properties.getProperty("kafka.topic.log.dwd.page");
        DataStreamSource<String> kafkaDS = env.addSource(CommonUtils.getKafkaConsumer(dwdPageTopic));

        //3. 将每行数据转换为 json 对象
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.map(JSON::parseObject);

        //4. 过滤数据 状态编程 只保留 mid 每天第一次登入的数据
        SingleOutputStreamOperator<JSONObject> uvDS = jsonObjDS.keyBy(jsonObj -> jsonObj.getJSONObject("common").getString("mid"))
                .filter(new RichFilterFunction<JSONObject>() {
                    private ValueState<String> dateState;
                    private SimpleDateFormat simpleDateFormat;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

                        //设置状态ttl 并设置更新模式 当状态更新时 ttl重置
                        ValueStateDescriptor<String> stringValueStateDescriptor = new ValueStateDescriptor<>("date-state", String.class);
                        StateTtlConfig stateTtlConfig = StateTtlConfig.newBuilder(Time.hours(24))
                                .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                                .build();
                        stringValueStateDescriptor.enableTimeToLive(stateTtlConfig);

                        dateState = getRuntimeContext().getState(stringValueStateDescriptor);
                    }

                    @Override
                    public boolean filter(JSONObject jsonObject) throws Exception {
                        //取出上一跳页面信息
                        String lastPageId = jsonObject.getJSONObject("page").getString("last_page_id");

                        //上一跳页面是否存在
                        if (lastPageId == null || lastPageId.length() <= 0) {
                            //取出状态数据
                            String lastDate = dateState.value();

                            //获取当前行为日期
                            String currentDate = simpleDateFormat.format(jsonObject.getLong("ts"));

                            //判断两个日期是否相等,只有不相等才为当前用户当天第一次访问
                            if (!currentDate.equals(lastDate)) {
                                dateState.update(currentDate);
                                return true;
                            }
                        }
                        return false;
                    }
                });

        //5. 将数据写入 kafka
        uvDS.print();
        String dwmUvTopic = properties.getProperty("kafka.topic.log.dwm.uv");
        uvDS.map(JSONAware::toJSONString).addSink(CommonUtils.getKafkaProducer(dwmUvTopic));

        //6. 启动任务
        env.execute("UniqueVisitApp");
    }
}
